<template>

    <el-dialog title="修改密码" :visible="true" width="600px" @close="$emit('close')">
        <div style="padding-right: 40px">
            <el-form :model="form" v-loading="loading" ref="form" :rules="rules"  label-width="120px">
                <el-form-item label="原密码" prop="password">
                    <el-input v-model="form.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="new_password">
                    <el-input v-model="form.new_password" :type="passwordVisible ? 'text' : 'password'">
                        <i slot="suffix" v-if="passwordVisible === true" class="fa fa-eye" @click="passwordVisible = !passwordVisible"></i>
                        <i slot="suffix" v-else class="fa fa-eye-slash" @click="passwordVisible = !passwordVisible"></i>
                    </el-input>
                </el-form-item>
            </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="$emit('close')">取消</el-button>
            <el-button :loading="submitting" type="primary" @click="submit">提交</el-button>
        </span>
    </el-dialog>

</template>

<script>
    import axios from 'axios'

    export default {
        data() {
            return {
                loading: false,
                submitting: false,
                form: {
                    password: null,
                    new_password: null,
                },
                passwordVisible: false,
                rules: {
                    password: [{required: true, message: '不能为空', trigger: 'blur'}],
                    new_password: [{required: true, min: 8, message: '至少为8位', trigger: 'blur'}],
                }
            }
        },
        methods: {
            submit() {
                this.$refs['form'].validate(async valid => {
                    if (!valid) return;
                    if (this.form.password === this.form.new_password) {
                        this.$message.error('新旧密码一样');
                        return;
                    }

                    this.submitting = true;
                    try {
                        await axios.post('/password', this.form);
                        this.$message.success('修改成功');
                        this.$emit('close')
                    } catch (e) {

                    }
                    this.submitting = false;
                })
            }
        }
    }
</script>